﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Castle.Services.Transaction;
using Castle.Facilities.IBatisNetIntegration;
using System.Data;
using Meqs.Entity;
using Meqs.Logic.Interface;

namespace Meqs.Logic.Implement
{
    [Transactional]
    [UsesAutomaticSessionCreation]
    public class StudentInfoLogic : CommonLogic<StudentInfo, int>, IStudentInfoLogic
    {

        #region Implementation of ICommonLogic<StudentInfo, int>

        /// <sammury>
        /// 创建对象
        /// </sammury>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Create(StudentInfo entity)
        {
            return CreateObject(entity);
        }

        /// <sammury>
        /// 更新对象
        /// </sammury>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update(StudentInfo entity)
        {
            return UpdateObject(entity);
        }

        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public int Delete(int entityId)
        {
            return DeleteObject(entityId);
        }

        /// <summary>
        /// 删除所有对象
        /// </summary>
        /// <returns></returns>
        public int DeleteAll()
        {
            return DeleteAllObject();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public StudentInfo FindById(int entityId)
        {
            return FindObjectById(entityId);
        }

        /// <summary>
        /// 检索对象数量
        /// </summary>
        /// <returns></returns>
        public int FindCount()
        {
            return FindObjectByCount();
        }

        /// <sammury>
        /// 检索对象
        /// </sammury>
        public IList<StudentInfo> FindAll()
        {
            return FindAllObject();
        }

        /// <summary>
        /// 检索对象数量
        /// </summary>
        /// <returns></returns>
        public int FindCount(Hashtable table)
        {
            return FindObjectByCount(table);
        }

        /// <sammury>
        /// 检索对象
        /// </sammury>
        public IList<StudentInfo> FindAll(Hashtable table)
        {
            return FindObject(table);
        }

        #endregion

        /// <summary>
        /// 删除所有用户信息
        /// </summary>
        /// <param name="listUserId"></param>
        /// <returns></returns>
        [Transaction(TransactionMode.Requires)]
        public int DeleteStudentInfo(List<int> listUserId)
        {
            foreach (int userId in listUserId)
            {
                StudentInfo studentInfo = FindById(userId);
                if (studentInfo != null)
                {
                    studentInfo.IsEffect = false;
                    Update(studentInfo);
                    Hashtable ht = new Hashtable();
                    ht.Add("StudentID", userId);
                    ht.Add("ClassID", studentInfo.ClsID);
                    string statementName = "StudentHistory.DeleteStudentHistory";
                    ExecuteDelete(statementName, ht);
                }
            }
            return 1;
        }

        /// <summary>
        /// 重置用户密码，可批量
        /// </summary>
        /// <param name="listUserId"></param>
        /// <returns></returns>
        [Transaction(TransactionMode.Requires)]
        public int ResetPassword(List<int> listUserId)
        {
            foreach (int userId in listUserId)
            {
                UpdateCustomer("StudentInfo.ResetPassword", userId);
            }
            return 1;
        }

        /// <summary>
        /// 将List里面的学生的密码全部更改为strPwd
        /// </summary>
        /// <param name="strPwd"></param>
        /// <param name="listUserId"></param>
        /// <returns></returns>
        [Transaction(TransactionMode.Requires)]
        public int ResetPassword(string strPwd, List<int> listUserId)
        {
            foreach (int userId in listUserId)
            {
                Hashtable ht = new Hashtable();
                ht.Add("RID", userId);
                ht.Add("Passwd", strPwd);

                UpdateCustomer("StudentInfo.CustomResetPassword", ht);
            }
            return 1;
        }


        /// 根据学生学号更新学生信息
        /// </summary>
        /// <param name="listUserId"></param>
        /// <returns></returns>
        public int UpdateByStudentCode(SchoolInfo si,ClsInfo ci,StudentInfo studentInfo)
        {
            Hashtable table = new Hashtable();
            table.Add("StudentCode", studentInfo.StudentCode);
            table.Add("IsEffect", 1);
            IList<StudentInfo> st = FindAll(table);

            Hashtable ht = new Hashtable();
            if (st.Count > 0)
            {
                ht.Add("StudentID", st[0].RID);
                ht.Add("SchoolYear", si.SchoolYear);
                ht.Add("Term", si.SchoolTerm);
                string statementName = "StudentHistory.DeleteStudentHistory";
                ExecuteDelete(statementName, ht);

                StudentHistory studenth = new StudentHistory();
                studenth.ClassID = studentInfo.ClsID;
                studenth.Grade = ci.Grade;
                studenth.SchoolYear = si.SchoolYear;
                studenth.Term = si.SchoolTerm;
                studenth.StudentID = st[0].RID;
                ExecuteInsert("StudentHistory.Insert", studenth);
            }


            return UpdateCustomer("StudentInfo.UpdateByStudentCode", studentInfo);
        }

        /// <summary>
        /// 导入学生数据
        /// </summary>
        /// <param name="listUserId"></param>
        /// <returns> </returns>
        [Transaction(TransactionMode.Requires)]
        public int ImportStudentInfo(string schoolMark, int clsID, DataTable dt, int opType)
        {
            //0列，学号
            //1列，姓名
            //2列，性别
            //3列，出生日期
            //4列，入学日期
            string time = "1800-1-1 00:00:00";
            DateTime minTime = Convert.ToDateTime(time);
            
            StudentInfo studentInfo = new StudentInfo();
            Hashtable ht = new Hashtable();
            ht.Add("SchoolMark", schoolMark);
            IList<SchoolInfo> listSchoolInfo = ExecuteQueryForList<SchoolInfo>("SchoolInfo.Find", ht);
            ht = new Hashtable();
            ht.Add("RID", clsID);
            ClsInfo ci = ExecuteQueryForObject<ClsInfo>("ClsInfo.FindById", ht); 
            int iUpdateRes = 0;
            int iInsertRes = 0;

            foreach (DataRow row in dt.Rows)
            {
                studentInfo.ClsID = clsID;
                studentInfo.IsEffect = true;
                studentInfo.SchoolMark = schoolMark;

                studentInfo.StudentCode = row[0].ToString();
                studentInfo.StudentName = row[1].ToString();
                studentInfo.StudentCode.Trim();
                studentInfo.StudentName.Trim();

                if (studentInfo.StudentCode == "" || studentInfo.StudentName == "")
                    continue;

                try { studentInfo.Sexy = Convert.ToInt16(row[2]); }
                catch { studentInfo.Sexy = 0; }

                try 
                { 
                    studentInfo.Birthday = DateTime.Parse(row[3].ToString());
                    if (DateTime.Compare(minTime, studentInfo.Birthday) >= 0)
                        studentInfo.Birthday = DateTime.MaxValue;
                }
                catch { studentInfo.Birthday = DateTime.MaxValue; }

                try 
                {
                    studentInfo.InSchoolDate = DateTime.Parse(row[4].ToString());
                    if (DateTime.Compare(minTime, studentInfo.InSchoolDate) >= 0)
                        studentInfo.InSchoolDate = DateTime.MaxValue;
                }
                catch { studentInfo.InSchoolDate = DateTime.MaxValue; }

                if (opType == 1)                        //覆盖已经存在的学生数据
                    iUpdateRes = UpdateByStudentCode(listSchoolInfo[0], ci, studentInfo);

                if (opType == 0)                        //不覆盖已经存在的学生数据
                    iUpdateRes = 0;

                //如果更新失败则直接添加学生数据
                if (iUpdateRes == 0)
                {
                    studentInfo.StudentCode = row[0].ToString();
                    studentInfo.StudentName = row[1].ToString();
                    studentInfo.Passwd = "123456";

                    try { studentInfo.Sexy = Convert.ToInt16(row[2]); }
                    catch { studentInfo.Sexy = 0; }

                    try
                    {
                        studentInfo.Birthday = DateTime.Parse(row[3].ToString());
                        if (DateTime.Compare(minTime, studentInfo.Birthday) >= 0)
                            studentInfo.Birthday = DateTime.MaxValue;
                    }
                    catch { studentInfo.Birthday = DateTime.MaxValue; }

                    try
                    {
                        studentInfo.InSchoolDate = DateTime.Parse(row[4].ToString());
                        if (DateTime.Compare(minTime, studentInfo.InSchoolDate) >= 0)
                            studentInfo.InSchoolDate = DateTime.MaxValue;
                    }
                    catch { studentInfo.InSchoolDate = DateTime.MaxValue; }

                    studentInfo.ClsID = clsID;
                    studentInfo.IsEffect = true;
                    studentInfo.SchoolMark = schoolMark;

                    Hashtable hs = new Hashtable();
                    hs.Add("StudentCode", studentInfo.StudentCode);
                    //hs.Add("IsEffect", studentInfo.IsEffect);
                    hs.Add("SchoolMark", studentInfo.SchoolMark);

                    List<StudentInfo> list = (List<StudentInfo>)FindAll(hs);
                    if (list.Count == 0)                        //未查找到相同数据 
                    {
                        
                        

                        iInsertRes = CreateObject(studentInfo);
                        StudentHistory studenth = new StudentHistory();
                        studenth.ClassID = studentInfo.ClsID;
                        studenth.Grade = ci.Grade;
                        studenth.SchoolYear = listSchoolInfo[0].SchoolYear;
                        studenth.Term = listSchoolInfo[0].SchoolTerm;
                        studenth.StudentID = iInsertRes;
                        ExecuteInsert("StudentHistory.Insert", studenth);

                        if (iInsertRes <= 0)
                            return 0;
                    }


                    //if (opType == 1)                                //直接添加教师数据
                    //    iInsertRes = CreateObject(studentInfo);

                    //if (opType == 0)                                //先判断该数据是否存在，再添加教师数据
                    //{
                    //    Hashtable hs = new Hashtable();
                    //    hs.Add("StudentCode", studentInfo.StudentCode);
                    //    hs.Add("IsEffect", studentInfo.IsEffect);
                    //    hs.Add("SchoolMark", studentInfo.SchoolMark);

                    //    List<StudentInfo> list = (List<StudentInfo>)FindAll(hs);
                    //    if (list.Count == 0)                        //未查找到相同数据 
                    //        iInsertRes = CreateObject(studentInfo);
                    //    else
                    //        iInsertRes = 1;                         //不需要添加数据时直接返回正确的插入结果
                    //}

                    //if (iInsertRes <= 0)
                    //    return 0;
                }

            }

            return 1;
        }


        public int CheckLogin(string schoolCode, string stuCode, string pass)
        {
            Hashtable ht = new Hashtable();
            ht.Add("SchoolCode", schoolCode);//学校编号
            ht.Add("IsEffect", true);//是否有效
            IList<SchoolInfo> chlList = this.ExecuteQueryForList<SchoolInfo>("SchoolInfo.Find", ht);
            //判断学校编号的合法性
            if (chlList.Count <= 0)//学校编号错误
            {
                return 0;
            }
            ht.Clear();
            string schoolMark = chlList[0].SchoolMark;
            ht.Add("IsEffect", true);
            ht.Add("SchoolMark", schoolMark);
            ht.Add("StudentCode", stuCode);
            //判断用户合法性
            IList<StudentInfo> list = this.ExecuteQueryForList<StudentInfo>("StudentInfo.Find", ht);
            if (list.Count <= 0)//用户名错误
            {
                return 1;
            }
            if (list[0].Passwd != pass)//密码错误
            {
                return 2;
            }
            Perm perm = new Perm();
            perm.UserType = 5;//用户类型
            perm.SchoolMark = schoolMark;//学校标识
            perm.SchoolName = chlList[0].SchoolName;
            perm.DataUserName = "S" + chlList[0].RID;//学校数据库用户名
            perm.UserName = stuCode;//学号
            perm.UName = list[0].StudentName;//学生姓名
            perm.UID = list[0].RID;
            /////////////////////////////////////////////////////////
            perm.SchoolAreaId = chlList[0].AreaID;
            ht.Clear();
            ht.Add("RID", chlList[0].AreaID);
            SchoolArea schoolArea = this.ExecuteQueryForObject<SchoolArea>("SchoolArea.FindById", ht);
            if (schoolArea != null)
            {
                perm.SchoolAreaName = schoolArea.SchoolAreaName;
            }

            HttpCookie shlMark = new HttpCookie("SchoolMark", schoolCode);
            shlMark.Expires = DateTime.Now.AddMonths(12);
            HttpContext.Current.Response.AppendCookie(shlMark);

            HttpCookie loginWayCookie = new HttpCookie("LoginWay", "1");
            loginWayCookie.Expires = DateTime.Now.AddMonths(12);
            HttpContext.Current.Response.AppendCookie(loginWayCookie);
            HttpContext.Current.Session["UserInfo"] = perm;
            return 3;
        }

        /// <summary>
        /// 获取学生信息
        /// </summary>
        /// <param name="schoolMark"></param>
        /// <param name="clsID"></param>
        /// <returns></returns>
        public IList<StudentInfo> GetStudentByCls(string schoolMark, int clsID)
        {
            Hashtable ht = new Hashtable();
            ht.Add("SchoolMark", schoolMark);
            ht.Add("ClsID", clsID);
            ht.Add("IsEffect", 1);
            return FindCustomer<StudentInfo>("StudentInfo.Find", ht);
        }

        /// <summary>
        /// 根据学号姓名查找学生
        /// </summary>
        public IList<StudentInfo> FindStudentByCodeAndName(string schoolMark, string param)
        {
            Hashtable ht = new Hashtable();
            ht.Add("SchoolMark", schoolMark);
            ht.Add("Param", param);
            return FindCustomer<StudentInfo>("StudentInfo.FindStudentByCodeAndName", ht);
        }

        /// <summary>
        /// 删除所有用户信息
        /// </summary>
        /// <param name="listUserId"></param>
        /// <returns></returns>
        [Transaction(TransactionMode.Requires)]
        public int ChangeStudentStatus(List<int> listUserId, int status)
        {
            foreach (int userId in listUserId)
            {
                StudentInfo studentInfo = FindById(userId);
                if (studentInfo != null)
                {
                    Hashtable ht = new Hashtable();
                    ht.Add("RID", userId);
                    ht.Add("Status", status);
                    ExecuteUpdate("StudentInfo.ChangeStatus", ht);
                    ht.Clear();
                    ht.Add("StudentID", userId);
                    ht.Add("ClassID", studentInfo.ClsID);
                    string statementName = "StudentHistory.DeleteStudentHistory";
                    ExecuteDelete(statementName, ht);
                }
            }
            return 1;
        }

        /// <summary>
        /// 获取学生信息
        /// </summary>
        /// <param name="schoolMark"></param>
        /// <param name="clsID"></param>
        /// <returns></returns>
        public IList<StudentInfo> FindAll1(Hashtable ht)
        {
            string statementName = "StudentInfo.Find1";
            return ExecuteQueryForList<StudentInfo>(statementName, ht);
        }
    }
}